import React, {useState, useRef, useEffect} from 'react';
import {ChevronDown, ChevronRight, ExternalLink, Trash2, FolderOpen, Edit3, Check, X, FolderInput} from 'lucide-react';
import {useDndMonitor} from '@dnd-kit/core';
import {SortableContext, rectSortingStrategy} from '@dnd-kit/sortable';
import {IconButton} from '@/components/ui/Button';
import {ConfirmModal} from '@/components/modals/Modal';
import {MoveCollectionModal} from '@/components/modals/MoveCollectionModal';
import {Tooltip} from '@/components/ui/Tooltip';
import {EditInput} from '@/components/ui/EditInput';
import {TabCard} from '@/components/cards/TabCard';
import {useToast} from '@/hooks/ui';
import {useDeleteCollection, useUpdateCollection} from '@/hooks/api/useCollections';
import {useSpaces} from '@/hooks/api';
import {openCollectionSmart} from '@/services';
import {formatCollectionTime, cn, getCollectionNameError} from '@/lib/utils';
import {usePreferencesStore, selectExpandedCollections, makeCollectionPreferenceKey} from '@/stores/preferences';
import type {SpaceCollection} from '@/types';

interface CollectionCardProps {
  collection: SpaceCollection;
  defaultExpanded?: boolean;
  className?: string;
  onEditingChange?: (isEditing: boolean) => void;
  disableInternalDrag?: boolean;
  isSortingContainer?: boolean;
}

const CollectionCardComponent: React.FC<CollectionCardProps> = ({
  collection,
  defaultExpanded = false,
  className,
  onEditingChange,
  disableInternalDrag = false,
  isSortingContainer = false,
}) => {
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isMoveModalOpen, setIsMoveModalOpen] = useState(false);
  const [isEditingTitle, setIsEditingTitle] = useState(false);
  const [editTitle, setEditTitle] = useState(collection.collection.name);
  const [titleError, setTitleError] = useState('');
  const titleInputRef = useRef<HTMLInputElement>(null);
  const cardHeaderRef = useRef<HTMLDivElement>(null);
  const [isAnyDragging, setIsAnyDragging] = useState(false);

  const expandedMap = usePreferencesStore(selectExpandedCollections);
  const setCollectionExpanded = usePreferencesStore((state) => state.setCollectionExpanded);
  const preferenceKey = makeCollectionPreferenceKey(collection.spaceId, collection.collectionId);
  const isExpanded = expandedMap[preferenceKey] ?? defaultExpanded ?? true;

  // 使用 TanStack Query mutations
  const deleteCollectionMutation = useDeleteCollection();
  const updateCollectionMutation = useUpdateCollection();
  
  const {data: spacesData} = useSpaces();
  const hasAvailableSpaces = (spacesData?.length ?? 0) > 1;
  const toast = useToast();

  const handleToggleExpanded = () => {
    setCollectionExpanded(collection.spaceId, collection.collectionId, !isExpanded);
  };

  const handleOpenAll = async () => {
    try {
      await openCollectionSmart(collection.collectionId);
    } catch (error) {
      console.error('打开集合失败:', error);
      toast.error('打开失败，请重试');
    }
  };

  const handleDelete = () => setIsDeleteModalOpen(true);

  const handleDeleteConfirm = async () => {
    setIsDeleting(true);
    try {
      await deleteCollectionMutation.mutateAsync({
        collectionId: collection.collectionId,
        spaceId: collection.spaceId,
      });
      toast.success('集合已删除');
      setIsDeleteModalOpen(false);
    } catch (error) {
      toast.error('删除失败，请重试');
    } finally {
      setIsDeleting(false);
    }
  };

  const handleDeleteCancel = () => setIsDeleteModalOpen(false);

  const handleStartEditTitle = () => {
    if (isEditingTitle) return;
    setEditTitle(collection.collection.name);
    setIsEditingTitle(true);
    setTitleError('');
    onEditingChange?.(true);
  };

  const handleSaveTitle = async () => {
    const trimmed = editTitle.trim();
    const err = getCollectionNameError(trimmed);
    if (err) {
      setTitleError(err);
      return;
    }
    if (trimmed === collection.collection.name) {
      setIsEditingTitle(false);
      setTitleError('');
      onEditingChange?.(false);
      return;
    }
    try {
      await updateCollectionMutation.mutateAsync({
        collectionId: collection.collectionId,
        spaceId: collection.spaceId,
        data: { name: trimmed },
      });
      toast.success('集合名称已更新');
      setIsEditingTitle(false);
      setTitleError('');
      onEditingChange?.(false);
    } catch (error) {
      console.error('更新标题失败:', error);
      toast.error('更新失败，请重试');
    }
  };

  const handleCancelEditTitle = () => {
    setEditTitle(collection.collection.name);
    setIsEditingTitle(false);
    setTitleError('');
    onEditingChange?.(false);
  };

  const handleTitleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value;
    setEditTitle(value);
    const err = getCollectionNameError(value);
    setTitleError(err || '');
  };

  useEffect(() => {
    if (!isEditingTitle) return;
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (cardHeaderRef.current?.contains(target)) return;
      handleCancelEditTitle();
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [isEditingTitle]);

  useEffect(() => {
    if (isEditingTitle && titleInputRef.current) {
      const input = titleInputRef.current;
      input.focus();
      const length = input.value.length;
      input.setSelectionRange(length, length);
    }
  }, [isEditingTitle]);

  return (
    <>
      <div className={cn('w-full border-b dark:border-gray-700', className)}>
        <div className="w-full my-6">
          <div ref={cardHeaderRef} className="flex items-center justify-between gap-3 px-3 py-6">
            <div className={cn('flex items-center gap-3', !isEditingTitle && 'overflow-hidden')}>
              <Tooltip content={isExpanded ? '折叠' : '展开'} side="top" variant="edit" disabled={isEditingTitle}>
                <IconButton
                  variant="ghost"
                  size="icon"
                  onClick={handleToggleExpanded}
                  disabled={isEditingTitle}
                  className="hover:text-primary-600 transition-colors"
                  icon={isExpanded ? <ChevronDown size={18}/> : <ChevronRight size={18}/>}
                  aria-label={isExpanded ? '折叠集合' : '展开集合'}
                />
              </Tooltip>

              <div className="flex-1 flex items-center gap-2 min-w-0">
                {isEditingTitle ? (
                  <div className="flex-1 flex flex-col gap-1">
                    <div className="flex items-center gap-2">
                      <EditInput
                        ref={titleInputRef}
                        value={editTitle}
                        onChange={handleTitleChange}
                        error={!!titleError}
                        errorMessage={titleError || undefined}
                        maxLength={100}
                        containerClassName="flex-1"
                      />
                      <div className="flex items-center gap-1">
                        <Tooltip content="确认" side="top">
                          <IconButton
                            variant="ghost"
                            size="sm"
                            onClick={handleSaveTitle}
                            disabled={!!getCollectionNameError(editTitle)}
                            className="hover:text-green-600 transition-colors"
                            icon={<Check size={16}/>}
                            aria-label="确认修改"
                          />
                        </Tooltip>
                        <Tooltip content="取消" side="top">
                          <IconButton
                            variant="ghost"
                            size="sm"
                            onClick={handleCancelEditTitle}
                            className="hover:text-red-600 transition-colors"
                            icon={<X size={16}/>}
                            aria-label="取消修改"
                          />
                        </Tooltip>
                      </div>
                    </div>
                  </div>
                ) : (
                  <>
                    <h3
                      onClick={handleToggleExpanded}
                      className="flex-1 truncate cursor-pointer text-xl font-semibold text-gray-900 dark:text-gray-100"
                    >
                      {collection.collection.name}
                    </h3>
                    <div className="flex items-center gap-2 text-sm text-gray-500">
                      <span className="flex items-center gap-1">
                        <FolderOpen size={16}/>
                        {collection.tabs.length} 个标签
                      </span>
                      <span title={formatCollectionTime(collection.collection.createdAt, collection.collection.updatedAt).tooltip}>
                        {formatCollectionTime(collection.collection.createdAt, collection.collection.updatedAt).text}
                      </span>
                    </div>
                  </>
                )}
              </div>
            </div>

            <div className="flex items-center gap-2">
              <Tooltip content="打开全部" side="top" disabled={isEditingTitle}>
                <IconButton
                  variant="ghost"
                  size="sm"
                  onClick={handleOpenAll}
                  disabled={isEditingTitle}
                  className="hover:text-blue-600"
                  icon={<ExternalLink size={16}/>}
                  aria-label="打开集合"
                />
              </Tooltip>
              <Tooltip content="修改标题" side="top" disabled={isEditingTitle}>
                <IconButton
                  variant="ghost"
                  size="sm"
                  onClick={handleStartEditTitle}
                  disabled={isEditingTitle}
                  className={cn('transition-colors', isEditingTitle ? 'text-gray-400 cursor-not-allowed' : 'hover:text-amber-600')}
                  icon={<Edit3 size={16}/>}
                  aria-label={isEditingTitle ? '正在编辑' : '修改标题'}
                />
              </Tooltip>
              {hasAvailableSpaces && (
                <Tooltip content="移动到" side="top" disabled={isEditingTitle}>
                  <IconButton
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      setIsMoveModalOpen(true);
                      onEditingChange?.(true);
                    }}
                    disabled={isEditingTitle}
                    className={cn('transition-colors', isEditingTitle ? 'text-gray-400 cursor-not-allowed' : 'hover:text-blue-600')}
                    icon={<FolderInput size={16}/>}
                    aria-label="移动到其他空间"
                  />
                </Tooltip>
              )}
              <Tooltip content="删除集合" side="top" variant="delete" disabled={isEditingTitle}>
                <IconButton
                  variant="ghost"
                  size="sm"
                  onClick={handleDelete}
                  disabled={isEditingTitle}
                  className={cn('transition-colors', isEditingTitle ? 'text-gray-400 cursor-not-allowed' : 'hover:text-danger-600')}
                  icon={<Trash2 size={16}/>}
                  aria-label="删除集合"
                />
              </Tooltip>
            </div>
          </div>

          {isExpanded && (
            <div className="px-6 pt-4 pb-8">
              {collection.tabs.length > 0 ? (
                <div>
                  {!disableInternalDrag && <DndGlobalDragWatcher onChange={setIsAnyDragging}/>} 
                  <SortableContext
                    items={collection.tabs.map((tab) => `tab-${tab.id}`)}
                    strategy={rectSortingStrategy}
                  >
                    <div
                      className="grid auto-rows-fr gap-5"
                      style={{gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 220px))', maxWidth: '1180px'}}
                    >
                      {collection.tabs.map((tab) => (
                        <TabCard
                          key={tab.id}
                          id={`tab-${tab.id}`}
                          tab={tab}
                          collectionId={collection.collectionId}
                          disableSorting={disableInternalDrag}
                          isAnyDragging={isAnyDragging}
                          isSortingContainer={isSortingContainer}
                        />
                      ))}
                    </div>
                  </SortableContext>
                </div>
              ) : (
                <div className="text-center py-8 text-sm text-gray-500 dark:text-gray-400">
                  <FolderOpen size={48} className="mx-auto mb-3 opacity-50"/>
                  <p className="text-sm">这个集合是空的</p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      <MoveCollectionModal
        collection={collection}
        isOpen={isMoveModalOpen}
        onClose={() => {
          setIsMoveModalOpen(false);
          onEditingChange?.(false);
        }}
      />

      <ConfirmModal
        open={isDeleteModalOpen}
        onClose={handleDeleteCancel}
        onConfirm={handleDeleteConfirm}
        title="删除集合"
        message={`确定要删除集合"${collection.collection.name}"吗？这将删除集合中的 ${collection.tabs.length} 个标签页，此操作不可恢复。`}
        confirmText="删除"
        confirmVariant="danger"
        loading={isDeleting}
      />
    </>
  );
};

const DndGlobalDragWatcher: React.FC<{onChange: (dragging: boolean) => void}> = ({onChange}) => {
  useDndMonitor({
    onDragStart: () => onChange(true),
    onDragEnd: () => onChange(false),
    onDragCancel: () => onChange(false),
  });
  return null;
};

export const CollectionCard = React.memo(CollectionCardComponent);
